import axios from 'axios'
import Messager from './messager';
import router from '@/router'
import store from '@/store'



const instance = axios.create({
    baseURL: process.env.VUE_APP_BASE_URL,
    timeout:  process.env.VUE_APP_TIMEOUT
})

instance.interceptors.request.use((config) => {
    // console.log(store,'store');
    let token = store.state.user.token
    if(token) {
        config.headers['Authorization'] = token
    }
    return config;
})

instance.interceptors.response.use(
    async (response) => {
        console.log(response, 'response', router)
        if (response.data.code == 401001 || response.data.code == 401002 || response.data.code == 401003) {
            console.log('请重新登录');
            Messager.error(response.data.msg)
            await store.dispatch('user/clearUserInfo')
            store.commit('modal/showComponentName','LoginBox')
            return Promise.reject(new Error(response.data.msg))
        } else if (response.data.code == 0) {
            return Promise.resolve(response.data.data)
        } else {
            Messager.error(response.data.msg)
            return Promise.reject(new Error(response.data.msg))
        }
    },
    error => {
        Messager.error('服务器发生错误')
        // console.log(error);
        return Promise.reject(error)
    }
)

export default instance
